﻿$(document).ready(function () {
        pageExecute.init();
});

var pageExecute = {
    fileContents: "Null",

    init: function() {
        $.ajaxSetup({ cache: true });

        // load package from server
        // Read menifest to start the startup page from module
        // parse the page to start and replace all scripts with inline scripts.
        // Update the browser history, iframe content, title to reflect the new view.
// Async package controller to return data in bytes or use another mech. to donwload the zip data

        $.get("api/package?packageName=Source", function(data) {
            //try {
                var buffer = window.atob(data);
                var zip = new JSZip(buffer);
                var content = zip.file("Index.html").asText();
                
                var xmlDocument = $($.parseXML(content));
                
                var scripts = xmlDocument.find("head>script");
                var scriptContent = "";
                for (var scriptIndex = 0; scriptIndex < scripts.length; scriptIndex++) {
                    var script = scripts[scriptIndex];
                    
                    if (script.src.length) {
                        xmlDocument.remove(script);
                        var scriptName = script.src.substring(script.src.lastIndexOf("/")).replace("/", "");
                        if (scriptName.length && zip.file(scriptName)) {
                            var jsFile = zip.file(scriptName).asText();
                            scriptContent += "<script> " + jsFile + " </script>";
                        }
                    }
                }

               scriptContent += '<script>$("body").load(OneApp.load());</script>';
                var $frame = $('#iframe');
                var doc = $frame[0].contentWindow.document;
                doc.write(content + scriptContent);
                setTimeout(function () {
                    $(document).attr("title", doc.title);
                    window.location.href = "Shell.html#Index.html";
                }, 1);

                
        });
    }
};
